/**
 * Copyright (c) 2019 Coder_League(码农联盟)
 * All rights reserved.
 *
 * File：MobileManagerService.java
 * History:
 *         2019年7月30日: Initially created, Liangj.
 */
package club.coderleague.ilsp.service.mobile.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import club.coderleague.ilsp.common.config.properties.FileUploadSettings;
import club.coderleague.ilsp.common.domain.beans.MobileUser;
import club.coderleague.ilsp.common.domain.beans.ResultMsg;
import club.coderleague.ilsp.common.domain.beans.mobile.MobileOrderDetails;
import club.coderleague.ilsp.common.domain.beans.mobile.MobileOrders;
import club.coderleague.ilsp.common.domain.beans.mobile.MoblieMerchantInfo;
import club.coderleague.ilsp.common.domain.beans.mobile.MoblieMerchantSettlementsInfo;
import club.coderleague.ilsp.common.domain.enums.EntityState;
import club.coderleague.ilsp.common.domain.enums.MemberBindType;
import club.coderleague.ilsp.common.domain.enums.OrderCancelType;
import club.coderleague.ilsp.common.domain.enums.OrderDeliveryState;
import club.coderleague.ilsp.common.domain.enums.OrderPaymentMode;
import club.coderleague.ilsp.common.domain.enums.OrderPaymentState;
import club.coderleague.ilsp.common.domain.enums.SettlementTypeEnums;
import club.coderleague.ilsp.common.exception.MessageInfoException;
import club.coderleague.ilsp.common.util.CommonUtil;
import club.coderleague.ilsp.dao.MemberBindDao;
import club.coderleague.ilsp.dao.MembersDao;
import club.coderleague.ilsp.dao.MerchantSettlementsDao;
import club.coderleague.ilsp.dao.MerchantsDao;
import club.coderleague.ilsp.dao.OrderGoodsDao;
import club.coderleague.ilsp.dao.OrdersDao;
import club.coderleague.ilsp.dao.ShoppingCartsDao;
import club.coderleague.ilsp.entities.Memberbinds;
import club.coderleague.ilsp.entities.Members;
import club.coderleague.ilsp.entities.Merchants;
import club.coderleague.ilsp.entities.Merchantsettlements;
import club.coderleague.ilsp.entities.Ordergoods;
import club.coderleague.ilsp.entities.Orders;
import club.coderleague.ilsp.entities.Shoppingcarts;
import club.coderleague.ilsp.service.capitalrecords.CapitalRecordsService;

/**
 * 手机管理界面
 * @author Liangjing
 */
@Service
public class MobileManagerService {
	
	@Autowired
	MerchantsDao merchantsDao;
	@Autowired 
	FileUploadSettings upload;
	@Autowired
	MerchantSettlementsDao merchantSettlementsDao;
	@Autowired
	CapitalRecordsService capitalRecordsService;
	@Autowired
	MembersDao membersDao;
	@Autowired
	MemberBindDao memberBindDao;
	@Autowired
	OrdersDao ordersDao;
	@Autowired
	OrderGoodsDao orderGoodsDao;
	@Autowired
	ShoppingCartsDao shoppingCartsDao;

	/**
	 * 获取对应商户的个人信息
	 * @author Liangjing 2019年7月30日
	 * @param merchantId
	 * @return
	 */
	public MoblieMerchantInfo getTheMerchantInfo(Long merchantid) {
		MoblieMerchantInfo info = merchantsDao.getTheMerchantInfo(merchantid);
		info.setMerchantphone(info.getMerchantphone().replace(info.getMerchantphone().substring(3, 7),"****"));
		info.setBcnumber(info.getBcnumber().replace(info.getBcnumber().substring(8, 16),"********"));
		info.setIdnumber(info.getIdnumber().replace(info.getIdnumber().substring(5, 13),"********"));
		info.setIdpositive(upload.getVirtual() + upload.getMerchantsPath() + info.getIdpositive());
		info.setIdnegative(upload.getVirtual() + upload.getMerchantsPath() + info.getIdnegative());
		info.setBusinesslicense(upload.getVirtual() + upload.getMerchantsPath() + info.getBusinesslicense());
		return info;
	}
	/**
	 * 更新商户短信通知或者自动结算
	 * @author Liangjing 2019年7月30日
	 * @param merchantid
	 * @param istate
	 * @param itype
	 * @return
	 */
	public ResultMsg updateTheMerchantSmNotifyOrAutoSettle(Long merchantid, Boolean istate, Integer itype) {
		Merchants merchants = merchantsDao.getOne(merchantid);
		if(itype == 1) {
			//短信通知
			merchants.setSmnotify(istate);
		}else if(itype == 2){
			//自动结算
			merchants.setAutosettle(istate);
		}
		return new ResultMsg(true, "操作成功");
	}
	
	/**
	 * 更新商户账户总额
	 * @author Liangjing 2019年7月30日
	 * @param entityid
	 * @param moeny
	 * @return
	 * @throws Exception 
	 */
	public ResultMsg updateTheMerchantMoeny(Long entityid, Double moeny) throws Exception{
		//验证
		Merchants merchants = merchantsDao.getOne(entityid);
		if(!merchants.getAutosettle()) {
			try {
				//锁定金额
				capitalRecordsService.updateLockCapitalByMerchantid(entityid, moeny);
			} catch (MessageInfoException e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return new ResultMsg(false, "账户余额不足");
			}
			Merchantsettlements merchantsettlements = new Merchantsettlements(EntityState.OBLIGATION.getValue(), entityid, SettlementTypeEnums.MANUAL.getValue(), moeny, new Date(), null, null, null, null, null, null);
			merchantSettlementsDao.save(merchantsettlements);
			return new ResultMsg(true, "操作成功");
		}else {
			return new ResultMsg(false, "已开启自动结算,不能手动操作");
		}
	}
	
	/**
	 * 获取对应商户所有结算数据
	 * @author Liangjing 2019年7月30日
	 * @param merchantid
	 * @return
	 */
	public List<Map<String,Object>> getTheAllMerchantSettlements(Long merchantid, List<String> istate) {
		return merchantSettlementsDao.getTheAllMerchantSettlements(merchantid, istate);
	}
	
	/**
	 * 获取对应结算数据详情
	 * @author Liangjing 2019年7月30日
	 * @param entityid
	 * @return
	 */
	public MoblieMerchantSettlementsInfo getTheMerchantSettlementInfo(Long entityid) {
		return merchantSettlementsDao.getTheMerchantSettlementInfo(entityid);
	}
	
	/**
	 * 撤销商户结算
	 * @author Liangjing 2019年7月30日
	 * @param entityid
	 * @return
	 * @throws Exception 
	 */
	public ResultMsg updateTheMerchantSettlementsToBack(Long entityid) throws Exception {
		Merchantsettlements merchantsettlements = merchantSettlementsDao.getOne(entityid);
		if(merchantsettlements.getEntitystate() != EntityState.OBLIGATION.getValue()) {
			return new ResultMsg(false, "该数据状态不是待处理状态");
		}
		try {
			capitalRecordsService.updateUnlockCapitalByMerchantid(merchantsettlements.getMerchantid(), merchantsettlements.getSettlementamount());
		} catch (MessageInfoException e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new ResultMsg(false, "锁定余额不足");
		}
		merchantsettlements.setEntitystate(EntityState.UNDO.getValue());
		merchantsettlements.setRevoketime(new Date());
		return new ResultMsg(true, "操作成功");
	}
	
	/**
	 * 获取手机用户个人信息
	 * @author Liangjing 2019年8月19日
	 * @param entityid
	 * @return
	 */
	public MobileUser getTheMobileUserInfo(Long entityid) {
		MobileUser mobileUser = membersDao.getTheMobileUserInfo(entityid);
		mobileUser.setMemberphone(mobileUser.getMemberphone().replace(mobileUser.getMemberphone().subSequence(3, 7), "****"));
		List<Map<String,Object>> list = memberBindDao.getTheMemberBindInfos(entityid);
		if(!CommonUtil.isEmpty(list)) {
			for (MemberBindType item : MemberBindType.values()) {
				boolean isadd = true;
				for (Map<String, Object> map : list) {
					if(item.getValue() == Integer.valueOf(map.get("bindtype").toString())) {
						isadd = false;
						break;
					}
				}
				if(isadd) {
					Map<String,Object> map = new HashMap<String, Object>();
					map.put("bindtype",item.getValue());
					map.put("isreal","0");
					list.add(map);
				}
			}
		}else {
			list = new ArrayList<Map<String,Object>>();
			for (MemberBindType item : MemberBindType.values()) {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("bindtype",item.getValue());
				map.put("isreal","0");
				list.add(map);
			}
		}
		mobileUser.setBindinfos(list);
		return mobileUser;
	}
	
	/**
	 * 修改会员昵称
	 * @author Liangjing 2019年8月19日
	 * @param entityid
	 * @param nickname
	 * @return
	 */
	public ResultMsg updateTheMemberNickName(Long entityid, String nickname) {
		Members members = membersDao.getOne(entityid);
		members.setNickname(nickname);
		return new ResultMsg(true, "操作成功");
	}
	
	/**
	 *  解除会员的绑定
	 * @author Liangjing 2019年8月19日
	 * @param entityid
	 * @return
	 */
	public ResultMsg updateTheMemberToRemoveBing(Long entityid) {
		Memberbinds memberbinds = memberBindDao.getOne(entityid);
		memberbinds.setEntitystate(EntityState.INVALID.getValue());
		return new ResultMsg(true, "操作成功");
	}
	
	/**
	 * -根据会员id获取会员信息。
	 * @author wangjb 2019年8月19日。
	 * @param memberid 会员信息。
	 * @return
	 */
	public Map<String, Object> getMemberInformationByMemberIdService(Long memberid) {
		Map<String, Object> result = new HashMap<String, Object>();
		Members members = this.membersDao.getOne(memberid);
		Long diamond = this.membersDao.getMemberDiamondByMemberIdDao(memberid); // 钻石。
		Long integral = this.membersDao.getMemberIntegralByMemberIdDao(memberid); // 积分。
		Long obligation = this.membersDao.getObligationByMemberIdDao(memberid); // 待付款。
		Long waitreceiv = this.membersDao.getWaitReceivByMemberIdDao(memberid); // 待收货。
		result.put("members", members);
		result.put("diamond", diamond);
		result.put("integral", integral);
		result.put("obligation", obligation);
		result.put("waitreceiv", waitreceiv);
		return result;
	}
	
	/**
	 * 获取会员对应待付款订单数量
	 * @author Liangjing 2019年8月28日
	 * @param memberid
	 * @return
	 */
	public Long getTheMemberWaitPayOrders(Long memberid) {
		return ordersDao.getTheMemberWaitPayOrders(memberid);
	}
	
	/**
	 * 获取会员对应待收货单数量
	 * @author Liangjing 2019年9月4日
	 * @param memberid
	 * @return
	 */
	public Long getTheMemberWaitTakeOrders(Long memberid) {
		return ordersDao.getTheMemberWaitTakeOrders(memberid);
	}
	
	/**
	 * 获取会员对应tab下标的订单详情
	 * @author Liangjing 2019年8月28日
	 * @param memberid
	 * @param tabIndex
	 * @return
	 */
	public List<MobileOrders> getTheOrdersByMemberidAndTabIndex(Long memberid, Integer tabIndex){
		Integer deliveryState = null;
		Integer paymentState = null;
		Integer entityidState = null;
		
		if(tabIndex == 1) {//全部
		}else if(tabIndex == 2) {//待付款
			entityidState = EntityState.CONFIRMED.getValue();
			paymentState = OrderPaymentState.UNPAID.getValue();
		}else if(tabIndex == 3) {//待发货
			entityidState = EntityState.CONFIRMED.getValue();
			deliveryState = OrderDeliveryState.UNSHIPPED.getValue();
			paymentState = OrderPaymentState.PAID.getValue();
		}else if(tabIndex == 4) {//待收货
			entityidState = EntityState.CONFIRMED.getValue();
			deliveryState = OrderDeliveryState.SHIPPED.getValue();
			paymentState = OrderPaymentState.PAID.getValue();
		}else if(tabIndex == 5) {//已完成
			entityidState = EntityState.OTS.getValue();
			deliveryState = OrderDeliveryState.RECEIVED.getValue();
		}else if(tabIndex == 6) {//已取消
			entityidState = EntityState.CANC.getValue();
		}
		
		List<MobileOrders> list = ordersDao.getTheOrdersByMemberidAndTabIndex(memberid, entityidState, deliveryState, paymentState);
		for (MobileOrders mobileOrders : list) {
			if("3".equals(mobileOrders.getOrderstate())|| "4".equals(mobileOrders.getOrderstate()) || "5".equals(mobileOrders.getOrderstate())) {
				mobileOrders.setIsnorefundtype(ordersDao.getTheOrderIsNoRefundType(mobileOrders.getOrderid()));
			}
			mobileOrders.setPiclist(orderGoodsDao.getAllGoodPictureByOrderId(mobileOrders.getOrderid(), upload.getVirtual() + upload.getGoodPhotosPath()));
		}
		
		return list;
	}
	
	/**
	 * 修改订单状态
	 * @author Liangjing 2019年8月29日
	 * @param orderid
	 * @return
	 */
	public ResultMsg updateTheOrderStata(Long orderid,Integer state) {
		Orders orders = ordersDao.getOne(orderid);
		if(state == EntityState.CANC.getValue()) {
			orders.setCanceltype(OrderCancelType.USER.getValue());
			orders.setCanceltime(new Date());
		}
		orders.setEntitystate(state);
		return new ResultMsg(true, "操作成功");
	}
	/**
	 * 获取对应订单详情
	 * @author Liangjing 2019年8月29日
	 * @param orderid
	 * @param tabIndex
	 * @return
	 */
	public MobileOrderDetails getTheMobileOrderDetailsByOrderidAndTabIndex(Long orderid, Integer orderstate) {
		MobileOrderDetails mobileOrderDetails = ordersDao.getTheMobileOrderDetailsByOrderidAndTabIndex(orderid, orderstate);
		if("3".equals(mobileOrderDetails.getOrderstate())|| "4".equals(mobileOrderDetails.getOrderstate()) || "5".equals(mobileOrderDetails.getOrderstate())) {
			mobileOrderDetails.setIsnorefundtype(ordersDao.getTheOrderIsNoRefundType(mobileOrderDetails.getOrderid()));
		}
		if(!CommonUtil.isEmpty(mobileOrderDetails.getReceivephone())) {
			mobileOrderDetails.setReceivephone(mobileOrderDetails.getReceivephone().replace(mobileOrderDetails.getReceivephone().substring(3, 7),"****"));
		}
		mobileOrderDetails.setGoodlist(orderGoodsDao.getAllGoodPictureInfoByOrderId(orderid, upload.getVirtual() + upload.getGoodPhotosPath()));
		return mobileOrderDetails;
	}
	/**
	 * 订单商品再次购买
	 * @author Liangjing 2019年8月30日
	 * @param orderid
	 * @return
	 */
	public ResultMsg updateTheAgainPayCar(Long orderid,Long memberid) {
		//删除购物车立即购买数据
		shoppingCartsDao.deleteShoppingCartsBuyNowData(memberid);
		
		List<Ordergoods> list = orderGoodsDao.findByOrderid(orderid);
		for (Ordergoods ordergoods : list) {
			Shoppingcarts shoppingcarts = shoppingCartsDao.findByMemberidAndSaleid(memberid, ordergoods.getSaleid());
			if(shoppingcarts != null) {
				shoppingcarts.setGoodnumber(shoppingcarts.getGoodnumber() + 1);
				if(!shoppingcarts.getSelectstate()) {
					shoppingcarts.setSelectstate(true);
				}
			}else {
				shoppingcarts = new Shoppingcarts(EntityState.VALID.getValue(), memberid, ordergoods.getSaleid(), 1.0, true, false);
				shoppingCartsDao.save(shoppingcarts);
			}
		}
		return new ResultMsg(true, "操作成功");
	}
	/**
	 * 修改订单支付方式
	 * @author Liangjing 2019年9月12日
	 * @param orderid
	 */
	public String updateTheOrderPayType(Long orderid) {
		Orders o = ordersDao.getOne(orderid);
		o.setPaymentmode(OrderPaymentMode.WECHAT.getValue());
		return OrderPaymentMode.WECHAT.getKey();
	}
}
